<?php

namespace app\index\middleware;

use think\facade\Db;
use think\facade\Session;
use think\exception\HttpResponseException;
use think\Response;

class Login
{
    public function handle($request, \Closure $next)
    {
//        登录验证
        $userinfo = session('userinfo');
        $islogin = true;
        $sessionid = Session::getId();
        if ($userinfo == null) {
//            保存密码验证
            $islogin = false;
            $cuserid = cookie('userid');
            $rememberSign = cookie('rememberSign');
            if ($cuserid != null && $rememberSign != null) {
                $user = Db::name('login')->find(['id' => $cuserid]);
                if ($user['rememberSign'] == $rememberSign && ($user['rememberTime'] >= $_SERVER['REQUEST_TIME'] || $user['rememberTime'] == 0)) {
                    $userinfo = Db::name('user')->find($user['id']);
                    session('userinfo', $userinfo);
                    $userinfo = $user;
                    cache($cuserid . '.session_id', $sessionid);
                    $islogin = true;
                }
            }
        }
        $isajax = $request->isAjax();
        if ($islogin) {
//            单点验证
            if ($sessionid != cache($userinfo['id'] . '.session_id')) {
                if ($isajax) {
                    $data['token'] = token();
                    $res = [
                        'code' => 2,
                        'data' => $data,
                        'msg' => '你的账户在其他客户端登录，请重新登录',
                        'url' => 'index.php/index/mine/login',
                        'time' => 2
                    ];
                    $response = Response::create($res, 'json')->options(['jump_template' => app()->config->get('app.dispatch_success_tmpl')]);
                    throw new HttpResponseException($response);
                } else {
                    return view('/error', ['msg' => '你的账户在其他客户端登录，请重新登录', 'time' => 5, 'url' => '/index.php/index/mine/login']);
                }
            }
            $request->userinfo = $userinfo;
            return $next($request);
        } else {
            if ($isajax) {
                $data['token'] = token();
                $res = [
                    'code' => 2,
                    'data' => $data,
                    'msg' => '请重新登录',
                    'url' => '/index.php/index/mine/login',
                    'time' => 2
                ];
                $response = Response::create($res, 'json')->options(['jump_template' => app()->config->get('app.dispatch_success_tmpl')]);
                throw new HttpResponseException($response);
            } else {
                return redirect('/index.php/index/mine/login');
            }
        }
    }
}
